package Utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.concurrent.CountDownLatch;

/**
 * @author Ken
 * @Description: TODO
 * @date 2021/1/20 17:50
 */
@Component
@Slf4j
public class SpringContextUtils implements ApplicationContextAware {

    /**
     * 使用闭锁来管理当spring容器还没有启动的时候被调用的问题
     */
    public static CountDownLatch latch = new CountDownLatch(1);

    /**
     * Spring应用上下文环境
     */
    private static ApplicationContext applicationContext;

    public static <T extends Object> T getBean(Class<T> beanClass) {
        return applicationContext.getBean(beanClass);
    }

    public static <T extends Object> T getBean(String beanName, Class<T> clz) {
        return applicationContext.getBean(beanName, clz);
    }

    public static String getActiveProfile() {
        return applicationContext.getEnvironment().getActiveProfiles()[0];
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

    /**
     * 获取对象 这里重写了bean方法，起主要作用
     *
     * @param name
     * @return Object 一个以所给名字注册的bean的实例
     * @throws BeansException
     */
    public static Object getBean(String name) throws BeansException {
        if (applicationContext == null) {
            try {
                latch.await();
            } catch (InterruptedException e) {
                log.error("Interrupt latch!", e);
                return null;
            }
        }
        return SpringContextUtils.applicationContext.getBean(name);
    }

}
